package cn.vshare.service.impl;

import cn.vshare.dao.FootprintDao;
import cn.vshare.entity.Footprint;
import cn.vshare.entity.Video;
import cn.vshare.service.FootprintService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service("footprintService")
public class FootprintServiceImpl implements FootprintService {

    @Autowired
    private FootprintDao footprintDao;

    /**
     * 向footprint表中写数据
     * 如果表中已存在某用户播放某一视频的记录时，只更新播放时间，不重新插入数据
     * 如果不存在则插入数据
     * @param footprint
     */
    @Override
    public void writeFootprint(Footprint footprint) {

        //查询记录是否存在
        Footprint footprint1=footprintDao.queryIsExistRecord(footprint.getUser().getId(),footprint.getVideo().getId());
        if(footprint1!=null){
            footprintDao.updateFootpoint(footprint);
        }else{
            footprint.setId(UUID.randomUUID().toString());//设置footprint id
            footprintDao.addFootprint(footprint);
        }
    }

    /**
     * 根据用户id查询历史足迹
     * @param cond
     * @return
     */
    @Override
    public Page<Footprint> queryFootprintByUid(Map<String,Object> cond) {
        Page<Footprint> page=new Page<>();
        //设置总记录数
        int count=footprintDao.queryFootprintByUidCount(cond);
        //获取页大小并赋值给page
        int pageSize=Integer.parseInt(String.valueOf(cond.get("pageSize")));
        //获取当前页码
        int curPageNum=Integer.parseInt(String.valueOf(cond.get("pageNo")));
        //计算总页数
        page.setTotal(count);
        page.setPageSize(pageSize);
        int totalPages=(count/ pageSize + (count % pageSize == 0 ? 0 : 1));
        page.setPageNum(totalPages);
        String uid= (String) cond.get("uid");
        page=PageHelper.startPage(curPageNum,pageSize);
        List<Footprint> footprintList=footprintDao.queryFootprintByUid(uid);
        return page;
    }

    /**
     * 分页查询用户收藏的视频
     * @param
     * @return
     */
    @Override
    public Page<Video> queryVideosIsFavorite(int pageNo, int pageSize, String uid) {
        Page<Video> page=PageHelper.startPage(pageNo,pageSize);
        List<Video> list=footprintDao.queryVideosIsFavorite(uid);
        page.setTotal(footprintDao.queryVideosCountIsFavorite(uid));
        return page;
    }


    @Override
    public Footprint queryIsExistRecord(String uid, String vid) {
        return footprintDao.queryIsExistRecord(uid, vid);
    }


}
